<template>
  <div>
    <div class="card">
      <div class="card-header">
        已选时间段内，群组在&nbsp;
        <el-tag type="warning" size="mini">{{ spaceRangeTip }}</el-tag>
        &nbsp;的贡献、活跃统计
      </div>
      <div class="card-content flex text-center" v-loading="loading" style="min-height: 5.8rem;">
        <div class="flex-1">
          <h2>{{ isNum(docsCount) ? docsCount : '--' }}</h2>
          <p>创建资源</p>
        </div>
        <div class="flex-1">
          <h2>{{ isNum(issuesCount) ? issuesCount : '--' }}</h2>
          <p>提出问题</p>
        </div>
        <div class="flex-1">
          <h2>{{ isNum(commentsCount) ? commentsCount : '--' }}</h2>
          <p>评论回复</p>
        </div>
      </div>
    </div>
    <global-activities-echarts
      :daterange="daterange"
      :chart-source="chartSource"
      :loading="loading"
      class="m-t-10"
    />
  </div>
</template>

<script>
import { formatActivities } from '@/views/groups/format';
import GlobalActivitiesEcharts from './global-activities-echarts';

export default {
  name: 'global-activities', // 群组活跃总况
  components: { GlobalActivitiesEcharts },
  props: {
    daterange: {
      type: Array,
      required: true,
    },
    selectedSpace: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      docsCount: undefined,
      issuesCount: undefined,
      commentsCount: undefined,
      chartSource: {
        docs: [],
        issues: [],
        comments: [],
      },
      loading: false,
    };
  },
  computed: {
    spaceRangeTip() {
      return this.selectedSpace.title
        ? `关联空间：${this.selectedSpace.title}`
        // : '全平台'; // 群组一对一绑定后，可能会延迟显示这部分内容
        : '--';
    },
    loadActivitiesParams() {
      return {
        groupId: this.$route.params.groupId,
        // spaceId: this.selectedSpace.id, // 群组一对一绑定后，后端获取spaceId
        daterange: this.daterange,
      };
    },
  },
  created() { this.loadActivities(); },
  methods: {
    loadActivities() {
      this.loading = true;
      this.$api.groups.activities(this.loadActivitiesParams)
        .then((res) => {
          if (res.data.wait) setTimeout(this.loadActivities, 2000);
          else {
            const result = formatActivities(res.data);
            this.docsCount = result.docsCount;
            this.issuesCount = result.issuesCount;
            this.commentsCount = result.commentsCount;
            Object.assign(this.chartSource, {
              docs: result.docs,
              issues: result.issues,
              comments: result.comments,
            });
            this.loading = false;
          }
        }).catch(() => { this.loading = false; });
    },
    resetCounts() {
      this.docsCount = undefined;
      this.issuesCount = undefined;
      this.commentsCount = undefined;
    },
  },
  watch: {
    loadActivitiesParams(val) {
      this.resetCounts();
      if (val.daterange.length) this.loadActivities(); // 有正确值再请求
    },
  },
};
</script>

<style></style>
